package com.wetest.uia2.stub;

import android.app.Instrumentation;
import android.app.UiAutomation;
import android.content.ClipData;
import android.content.Context;
import android.content.IOnPrimaryClipChangedListener;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Base64;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;

import androidx.test.uiautomator.Configurator;
import androidx.test.uiautomator.Direction;
import androidx.test.uiautomator.SearchCondition;
import androidx.test.uiautomator.StaleObjectException;
import androidx.test.uiautomator.UiAutomationHelper;
import androidx.test.uiautomator.UiCollection;
import androidx.test.uiautomator.UiDevice;
import androidx.test.uiautomator.UiObject;
import androidx.test.uiautomator.UiObject2;
import androidx.test.uiautomator.UiObjectNotFoundException;
import androidx.test.uiautomator.UiScrollable;
import androidx.test.uiautomator.UiSelector;
import androidx.test.uiautomator.Until;

import com.github.uiautomator.AutoTaskService;
import com.github.uiautomator.MainActivity;
import com.github.uiautomator.ToastHelper;
import com.wetest.uia2.Ln;
import com.wetest.uia2.Main;
import com.wetest.uia2.exceptions.NotImplementedException;
import com.wetest.uia2.stub.watcher.ClickUiObjectWatcher;
import com.wetest.uia2.stub.watcher.PressKeysWatcher;

import org.apache.commons.io.FileUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import proxy.Bridge;
import proxy.wrappers.ClipboardManager;
import uiautomator.InstrumentShellWrapper;

/* loaded from: classes9.dex */
public class AutomatorServiceImpl implements AutomatorService {
    ClipboardManager clipboardManager;
    private UiDevice device;
    private String lastToastMessage;
    private Instrumentation mInstrumentation;
    private TouchController touchController;
    private UiAutomation uiAutomation;
    private final HashSet<String> watchers = new HashSet<>();
    private final ConcurrentHashMap<String, UiObject> uiObjects = new ConcurrentHashMap<>();
    Handler handler = new Handler(Looper.getMainLooper());

    public AutomatorServiceImpl() {
//        InstrumentShellWrapper instrumentShellWrapper = InstrumentShellWrapper.getInstance();
//        this.mInstrumentation = instrumentShellWrapper;
//        this.device = UiDevice.getInstance(instrumentShellWrapper);
//        Ln.i("getProductName:" + device.getProductName() + "|DisplayRotation:" + device.getDisplayRotation());
//        UiAutomation uiAutomation = UiAutomationHelper.getUiAutomation();//uiDevice.getUiAutomation();
//        this.uiAutomation = uiAutomation;
//        this.touchController = new TouchController(instrumentShellWrapper);
//        Configurator configurator = Configurator.getInstance();
//        configurator.setWaitForSelectorTimeout(0L);
//        configurator.setWaitForIdleTimeout(0L);
//        configurator.setActionAcknowledgmentTimeout(500L);
//        configurator.setScrollAcknowledgmentTimeout(200L);
//        configurator.setKeyInjectionDelay(0L);
//        uiAutomation.setOnAccessibilityEventListener(new UiAutomation.OnAccessibilityEventListener() { // from class: com.wetest.uia2.stub.AutomatorServiceImpl$$ExternalSyntheticLambda0
//            @Override // android.app.UiAutomation.OnAccessibilityEventListener
//            public final void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
//                AutomatorServiceImpl.this.m15lambda$new$0$comwetestuia2stubAutomatorServiceImpl(accessibilityEvent);
//            }
//        });
//        Ln.i("clipboardManager inited");
//        ClipboardManager clipboardManager = Bridge.getInstance().getClipboardManager();
//        this.clipboardManager = clipboardManager;
//        clipboardManager.addPrimaryClipChangedListener(new IOnPrimaryClipChangedListener.Stub() { // from class: com.wetest.uia2.stub.AutomatorServiceImpl.1
//            @Override // android.content.IOnPrimaryClipChangedListener
//            public void dispatchPrimaryClipChanged() {
//                Ln.i("clipboard changes to:" + ((Object) AutomatorServiceImpl.this.clipboardManager.getText()));
//            }
//        });
    }

    /* renamed from: lambda$new$0$com-wetest-uia2-stub-AutomatorServiceImpl, reason: not valid java name */
    /* synthetic */ void m15lambda$new$0$comwetestuia2stubAutomatorServiceImpl(AccessibilityEvent event) {
        if (event.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
            CharSequence className = event.getClassName();
            Objects.requireNonNull(className);
            if (className.toString().contains(Toast.class.getName())) {
                Ln.i("detect toast:" + event.getText());
                String originText = event.getText().toString();
                this.lastToastMessage = originText.substring(1, originText.length() - 1);
            }
        }
    }

    private UiAutomation getUiAutomation() {
        return this.uiAutomation;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String ping() {
        return "pong";
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public DeviceInfo deviceInfo() {
        return DeviceInfo.getDeviceInfo();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean makeToast(final String text, final int duration) {
        this.handler.post(new Runnable() { // from class: com.wetest.uia2.stub.AutomatorServiceImpl.2
            @Override // java.lang.Runnable
            public void run() {
                ToastHelper.makeText(AutomatorServiceImpl.this.mInstrumentation.getTargetContext(), text, duration).show();
            }
        });
        return true;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String getLastToast() {
        return this.lastToastMessage;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void clearLastToast() {
        this.lastToastMessage = null;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean click(int x, int y) {
        if (x < 0 || y < 0) {
            return false;
        }
        this.touchController.touchDown(x, y);
        SystemClock.sleep(100L);
        return this.touchController.touchUp(x, y);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean click(int x, int y, long milliseconds) {
        if (x < 0 || y < 0) {
            return false;
        }
        this.touchController.touchDown(x, y);
        SystemClock.sleep(milliseconds);
        return this.touchController.touchUp(x, y);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean drag(int startX, int startY, int endX, int endY, int steps) throws NotImplementedException {
        return this.device.drag(startX, startY, endX, endY, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean swipe(int startX, int startY, int endX, int endY, int steps) {
        return this.device.swipe(startX, startY, endX, endY, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean swipePoints(int[] segments, int segmentSteps) {
        android.graphics.Point[] points = new android.graphics.Point[segments.length / 2];
        for (int i = 0; i < segments.length / 2; i++) {
            points[i] = new android.graphics.Point(segments[i * 2], segments[(i * 2) + 1]);
        }
        return this.device.swipe(points, segmentSteps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean injectInputEvent(int action, float x, float y, int metaState) {
        switch (action) {
            case 0:
                return this.touchController.touchDown(x, y);
            case 1:
                return this.touchController.touchUp(x, y);
            case 2:
                return this.touchController.touchMove(x, y);
            default:
                return false;
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String dumpWindowHierarchy(boolean compressed) {
        String xml = dumpWindowHierarchy(compressed, 50);
        File file = new File(MainActivity.context.getCacheDir(), "layout_xml.xml");
        try {
            FileUtils.write(file, xml, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xml;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String dumpWindowHierarchy(boolean compressed, int maxDepth) {
        if (AutoTaskService.accessibilityService == null) return "";
        Ln.i("dumpWindowHierarchy->compressed:" + compressed + "|maxDepth:" + maxDepth);
//        InstrumentShellWrapper.getInstance().setCompressedLayoutHierarchy(compressed);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            try {
                AccessibilityNodeInfoDumper.dumpWindowHierarchy(/*this.device,*/ os, maxDepth);
                String dumpXml = os.toString("UTF-8");
                Ln.i(dumpXml);
                return dumpXml;
            } finally {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        } catch (IOException e2) {
            Log.d("dumpWindowHierarchy got IOException: " + e2);
            try {
                os.close();
                return null;
            } catch (IOException e3) {
                return null;
            }
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String takeScreenshot(String filename, float scale, int quality) throws NotImplementedException {
        File f = new File(this.mInstrumentation.getTargetContext().getFilesDir(), filename);
        this.device.takeScreenshot(f, scale, quality);
        if (f.exists()) {
            return f.getAbsolutePath();
        }
        return null;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String takeScreenshot(float scale, int quality) throws NotImplementedException {
        Bitmap screenshot = getUiAutomation().takeScreenshot();
        if (screenshot == null) {
            return null;
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            try {
                screenshot.compress(Bitmap.CompressFormat.JPEG, quality, bos);
                bos.flush();
                return Base64.encodeToString(bos.toByteArray(), 0);
            } catch (IOException ioe) {
                Log.e("takeScreenshot error: " + ioe);
                try {
                    bos.close();
                } catch (IOException e) {
                }
                screenshot.recycle();
                return null;
            }
        } finally {
            try {
                bos.close();
            } catch (IOException e2) {
            }
            screenshot.recycle();
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void freezeRotation(boolean freeze) throws RemoteException {
        if (!freeze) {
            this.device.unfreezeRotation();
        } else {
            this.device.freezeRotation();
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void setOrientation(String dir) throws RemoteException, NotImplementedException {
        String dir2 = dir.toLowerCase();
        if ("left".equals(dir2) || "l".equals(dir2)) {
            this.device.setOrientationLeft();
            return;
        }
        if ("right".equals(dir2) || "r".equals(dir2)) {
            this.device.setOrientationRight();
        } else if ("natural".equals(dir2) || "n".equals(dir2)) {
            this.device.setOrientationNatural();
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String getLastTraversedText() {
        return this.device.getLastTraversedText();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void clearLastTraversedText() {
        this.device.clearLastTraversedText();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean openNotification() throws NotImplementedException {
        return this.device.openNotification();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean openQuickSettings() throws NotImplementedException {
        return this.device.openQuickSettings();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean hasWatcherTriggered(String watcherName) {
        return this.device.hasWatcherTriggered(watcherName);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean hasAnyWatcherTriggered() {
        return this.device.hasAnyWatcherTriggered();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void registerClickUiObjectWatcher(String name, Selector[] conditions, Selector target) {
        synchronized (this.watchers) {
            if (this.watchers.contains(name)) {
                this.device.removeWatcher(name);
                this.watchers.remove(name);
            }
            UiSelector[] selectors = new UiSelector[conditions.length];
            for (int i = 0; i < conditions.length; i++) {
                selectors[i] = conditions[i].toUiSelector();
            }
            this.device.registerWatcher(name, new ClickUiObjectWatcher(selectors, target.toUiSelector()));
            this.watchers.add(name);
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void registerPressKeyskWatcher(String name, Selector[] conditions, String[] keys) {
        synchronized (this.watchers) {
            if (this.watchers.contains(name)) {
                this.device.removeWatcher(name);
                this.watchers.remove(name);
            }
            UiSelector[] selectors = new UiSelector[conditions.length];
            for (int i = 0; i < conditions.length; i++) {
                selectors[i] = conditions[i].toUiSelector();
            }
            this.device.registerWatcher(name, new PressKeysWatcher(selectors, keys));
            this.watchers.add(name);
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void removeWatcher(String name) {
        synchronized (this.watchers) {
            if (this.watchers.contains(name)) {
                this.device.removeWatcher(name);
                this.watchers.remove(name);
            }
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void resetWatcherTriggers() {
        this.device.resetWatcherTriggers();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void runWatchers() {
        this.device.runWatchers();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String[] getWatchers() {
        String[] strArr;
        synchronized (this.watchers) {
            HashSet<String> hashSet = this.watchers;
            strArr = (String[]) hashSet.toArray(new String[hashSet.size()]);
        }
        return strArr;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean pressKey(String key) throws RemoteException {
        String key2 = key.toLowerCase();
        if (!"home".equals(key2)) {
            if (!"back".equals(key2)) {
                if (!"left".equals(key2)) {
                    if (!"right".equals(key2)) {
                        if (!"up".equals(key2)) {
                            if (!"down".equals(key2)) {
                                if (!"center".equals(key2)) {
                                    if (!"menu".equals(key2)) {
                                        if (!"search".equals(key2)) {
                                            if (!"enter".equals(key2)) {
                                                if ("delete".equals(key2) || "del".equals(key2)) {
                                                    boolean result = this.device.pressDelete();
                                                    return result;
                                                }
                                                if (!"recent".equals(key2)) {
                                                    if (!"volume_up".equals(key2)) {
                                                        if ("volume_down".equals(key2)) {
                                                            boolean result2 = this.device.pressKeyCode(25);
                                                            return result2;
                                                        }
                                                        if ("volume_mute".equals(key2)) {
                                                            boolean result3 = this.device.pressKeyCode(164);
                                                            return result3;
                                                        }
                                                        if (!"camera".equals(key2)) {
                                                            return "power".equals(key2) && this.device.pressKeyCode(26);
                                                        }
                                                        boolean result4 = this.device.pressKeyCode(27);
                                                        return result4;
                                                    }
                                                    boolean result5 = this.device.pressKeyCode(24);
                                                    return result5;
                                                }
                                                boolean result6 = this.device.pressRecentApps();
                                                return result6;
                                            }
                                            boolean result7 = this.device.pressEnter();
                                            return result7;
                                        }
                                        boolean result8 = this.device.pressSearch();
                                        return result8;
                                    }
                                    boolean result9 = this.device.pressMenu();
                                    return result9;
                                }
                                boolean result10 = this.device.pressDPadCenter();
                                return result10;
                            }
                            boolean result11 = this.device.pressDPadDown();
                            return result11;
                        }
                        boolean result12 = this.device.pressDPadUp();
                        return result12;
                    }
                    boolean result13 = this.device.pressDPadRight();
                    return result13;
                }
                boolean result14 = this.device.pressDPadLeft();
                return result14;
            }
            boolean result15 = this.device.pressBack();
            return result15;
        }
        boolean result16 = this.device.pressHome();
        return result16;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean pressKeyCode(int keyCode) {
        return this.device.pressKeyCode(keyCode);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean pressKeyCode(int keyCode, int metaState) {
        return this.device.pressKeyCode(keyCode, metaState);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void wakeUp() throws RemoteException {
        this.device.wakeUp();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void sleep() throws RemoteException {
        this.device.sleep();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean isScreenOn() throws RemoteException {
        return this.device.isScreenOn();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void waitForIdle(long timeout) {
        this.device.waitForIdle(timeout);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean waitForWindowUpdate(String packageName, long timeout) {
        return this.device.waitForWindowUpdate(packageName, timeout);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void clearTextField(Selector obj) throws UiObjectNotFoundException {
        try {
            obj.toUiObject2().clear();
        } catch (StaleObjectException | NullPointerException e) {
            this.device.findObject(obj.toUiSelector()).clearTextField();
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String getText(Selector obj) throws UiObjectNotFoundException {
        if (obj.toUiObject2() == null) {
            return this.device.findObject(obj.toUiSelector()).getText();
        }
        return obj.toUiObject2().getText();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean setText(Selector obj, String text) throws UiObjectNotFoundException {
        try {
            obj.toUiObject2().click();
            obj.toUiObject2().setText(text);
            return true;
        } catch (StaleObjectException | NullPointerException e) {
            return this.device.findObject(obj.toUiSelector()).setText(text);
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean click(Selector obj) throws UiObjectNotFoundException {
        if (obj.toUiObject2() == null) {
            return this.device.findObject(obj.toUiSelector()).click();
        }
        obj.toUiObject2().click();
        return true;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean click(Selector obj, String corner) throws UiObjectNotFoundException {
        return click(this.device.findObject(obj.toUiSelector()), corner);
    }

    private boolean click(UiObject obj, String corner) throws UiObjectNotFoundException {
        if (corner == null) {
            corner = "center";
        }
        String corner2 = corner.toLowerCase();
        if ("br".equals(corner2) || "bottomright".equals(corner2)) {
            return obj.clickBottomRight();
        }
        if ("tl".equals(corner2) || "topleft".equals(corner2)) {
            return obj.clickTopLeft();
        }
        if ("c".equals(corner2) || "center".equals(corner2)) {
            return obj.click();
        }
        return false;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean clickAndWaitForNewWindow(Selector obj, long timeout) throws UiObjectNotFoundException {
        if (obj.toUiObject2() == null) {
            return this.device.findObject(obj.toUiSelector()).clickAndWaitForNewWindow(timeout);
        }
        return ((Boolean) obj.toUiObject2().clickAndWait(Until.newWindow(), timeout)).booleanValue();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean longClick(Selector obj) throws UiObjectNotFoundException {
        if (obj.toUiObject2() == null) {
            return this.device.findObject(obj.toUiSelector()).longClick();
        }
        obj.toUiObject2().longClick();
        return true;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean longClick(Selector obj, String corner) throws UiObjectNotFoundException {
        return longClick(this.device.findObject(obj.toUiSelector()), corner);
    }

    private boolean longClick(UiObject obj, String corner) throws UiObjectNotFoundException {
        if (corner == null) {
            corner = "center";
        }
        String corner2 = corner.toLowerCase();
        if ("br".equals(corner2) || "bottomright".equals(corner2)) {
            return obj.longClickBottomRight();
        }
        if ("tl".equals(corner2) || "topleft".equals(corner2)) {
            return obj.longClickTopLeft();
        }
        if ("c".equals(corner2) || "center".equals(corner2)) {
            return obj.longClick();
        }
        return false;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean dragTo(Selector obj, Selector destObj, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return dragTo(this.device.findObject(obj.toUiSelector()), destObj, steps);
    }

    private boolean dragTo(UiObject obj, Selector destObj, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return obj.dragTo(this.device.findObject(destObj.toUiSelector()), steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean dragTo(Selector obj, int destX, int destY, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return dragTo(this.device.findObject(obj.toUiSelector()), destX, destY, steps);
    }

    private boolean dragTo(UiObject obj, int destX, int destY, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return obj.dragTo(destX, destY, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean exist(Selector obj) {
        if (obj.getChildOrSibling().length == 0 && (obj.getMask() & Selector.MASK_INDEX) == 0) {
            return this.device.findObject(obj.toBySelector()) != null;
        }
        return this.device.findObject(obj.toUiSelector()).exists();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public ObjInfo objInfo(Selector obj) throws UiObjectNotFoundException {
        UiObject2 obj2 = obj.toUiObject2();
        if (obj2 != null) {
            return ObjInfo.getObjInfo(obj2);
        }
        return ObjInfo.getObjInfo(this.device.findObject(obj.toUiSelector()));
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public int count(Selector obj) {
        if ((obj.deepSelector().getMask() & Selector.MASK_INSTANCE) > 0) {
            return this.device.findObject(obj.toUiSelector()).exists() ? 1 : 0;
        }
        UiSelector sel = obj.toUiSelector();
        if (!this.device.findObject(sel).exists()) {
            return 0;
        }
        int low = 1;
        int high = 2;
        UiSelector sel2 = obj.toUiSelector(2 - 1);
        while (this.device.findObject(sel2).exists()) {
            low = high;
            high *= 2;
            sel2 = obj.toUiSelector(high - 1);
        }
        while (high > low + 1) {
            int mid = (low + high) / 2;
            UiSelector sel3 = obj.toUiSelector(mid - 1);
            if (this.device.findObject(sel3).exists()) {
                low = mid;
            } else {
                high = mid;
            }
        }
        return low;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public ObjInfo[] objInfoOfAllInstances(Selector obj) {
        int total = count(obj);
        ObjInfo[] objs = new ObjInfo[total];
        if ((obj.getMask() & Selector.MASK_INSTANCE) > 0 && total > 0) {
            try {
                objs[0] = objInfo(obj);
            } catch (UiObjectNotFoundException e) {
            }
        } else {
            UiSelector sel = obj.toUiSelector();
            for (int i = 0; i < total; i++) {
                try {
                    objs[i] = ObjInfo.getObjInfo(sel.instance(i));
                } catch (UiObjectNotFoundException e2) {
                }
            }
        }
        return objs;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean gesture(Selector obj, Point startPoint1, Point startPoint2, Point endPoint1, Point endPoint2, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return gesture(this.device.findObject(obj.toUiSelector()), startPoint1, startPoint2, endPoint1, endPoint2, steps);
    }

    private boolean gesture(UiObject obj, Point startPoint1, Point startPoint2, Point endPoint1, Point endPoint2, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return obj.performTwoPointerGesture(startPoint1.toPoint(), startPoint2.toPoint(), endPoint1.toPoint(), endPoint2.toPoint(), steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean pinchIn(Selector obj, int percent, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return pinchIn(this.device.findObject(obj.toUiSelector()), percent, steps);
    }

    private boolean pinchIn(UiObject obj, int percent, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return obj.pinchIn(percent, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean pinchOut(Selector obj, int percent, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return pinchOut(this.device.findObject(obj.toUiSelector()), percent, steps);
    }

    private boolean pinchOut(UiObject obj, int percent, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return obj.pinchOut(percent, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean swipe(Selector obj, String dir, int steps) throws UiObjectNotFoundException {
        return swipe(this.device.findObject(obj.toUiSelector()), dir, steps);
    }

    private boolean swipe(UiObject item, String dir, int steps) throws UiObjectNotFoundException {
        String dir2 = dir.toLowerCase();
        if ("u".equals(dir2) || "up".equals(dir2)) {
            boolean result = item.swipeUp(steps);
            return result;
        }
        if ("d".equals(dir2) || "down".equals(dir2)) {
            boolean result2 = item.swipeDown(steps);
            return result2;
        }
        if ("l".equals(dir2) || "left".equals(dir2)) {
            boolean result3 = item.swipeLeft(steps);
            return result3;
        }
        if (!"r".equals(dir2) && !"right".equals(dir2)) {
            return false;
        }
        boolean result4 = item.swipeRight(steps);
        return result4;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean swipe(Selector obj, String dir, float percent, int steps) throws UiObjectNotFoundException {
        if (obj.toUiObject2() == null) {
            return swipe(this.device.findObject(obj.toUiSelector()), dir, steps);
        }
        return swipe(obj.toUiObject2(), dir, percent, steps);
    }

    private boolean swipe(UiObject2 item, String dir, float percent, int steps) throws UiObjectNotFoundException {
        String dir2 = dir.toLowerCase();
        if ("u".equals(dir2) || "up".equals(dir2)) {
            item.swipe(Direction.UP, percent, steps);
            return true;
        }
        if ("d".equals(dir2) || "down".equals(dir2)) {
            item.swipe(Direction.DOWN, percent, steps);
            return true;
        }
        if ("l".equals(dir2) || "left".equals(dir2)) {
            item.swipe(Direction.LEFT, percent, steps);
            return true;
        }
        if ("r".equals(dir2) || "right".equals(dir2)) {
            item.swipe(Direction.RIGHT, percent, steps);
            return true;
        }
        return true;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean waitForExists(Selector obj, long timeout) {
        try {
            if (obj.getChildOrSibling().length == 0 && !obj.checkBySelectorNull(obj)) {
                return ((Boolean) this.device.wait((SearchCondition) Until.hasObject(obj.toBySelector()), timeout)).booleanValue();
            }
        } catch (ClassCastException e) {
            Log.d("waitForExists got ClassCastException " + e);
        }
        return this.device.findObject(obj.toUiSelector()).waitForExists(timeout);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean waitUntilGone(Selector obj, long timeout) {
        try {
            if (obj.getChildOrSibling().length == 0 && !obj.checkBySelectorNull(obj)) {
                return ((Boolean) this.device.wait((SearchCondition) Until.gone(obj.toBySelector()), timeout)).booleanValue();
            }
        } catch (ClassCastException e) {
            Log.d("waitUntilGone got ClassCastException " + e);
        }
        return this.device.findObject(obj.toUiSelector()).waitUntilGone(timeout);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean flingBackward(Selector obj, boolean isVertical) throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(obj.toUiSelector());
        if (isVertical) {
            scrollable.setAsVerticalList();
        } else {
            scrollable.setAsHorizontalList();
        }
        return scrollable.flingBackward();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean flingForward(Selector obj, boolean isVertical) throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(obj.toUiSelector());
        if (isVertical) {
            scrollable.setAsVerticalList();
        } else {
            scrollable.setAsHorizontalList();
        }
        return scrollable.flingForward();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean flingToBeginning(Selector obj, boolean isVertical, int maxSwipes) throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(obj.toUiSelector());
        if (isVertical) {
            scrollable.setAsVerticalList();
        } else {
            scrollable.setAsHorizontalList();
        }
        return scrollable.flingToBeginning(maxSwipes);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean flingToEnd(Selector obj, boolean isVertical, int maxSwipes) throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(obj.toUiSelector());
        if (isVertical) {
            scrollable.setAsVerticalList();
        } else {
            scrollable.setAsHorizontalList();
        }
        return scrollable.flingToEnd(maxSwipes);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean scrollBackward(Selector obj, boolean isVertical, int steps) throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(obj.toUiSelector());
        if (isVertical) {
            scrollable.setAsVerticalList();
        } else {
            scrollable.setAsHorizontalList();
        }
        return scrollable.scrollBackward(steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean scrollForward(Selector obj, boolean isVertical, int steps) throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(obj.toUiSelector());
        if (isVertical) {
            scrollable.setAsVerticalList();
        } else {
            scrollable.setAsHorizontalList();
        }
        return scrollable.scrollForward(steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean scrollToBeginning(Selector obj, boolean isVertical, int maxSwipes, int steps) throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(obj.toUiSelector());
        if (isVertical) {
            scrollable.setAsVerticalList();
        } else {
            scrollable.setAsHorizontalList();
        }
        return scrollable.scrollToBeginning(maxSwipes, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean scrollToEnd(Selector obj, boolean isVertical, int maxSwipes, int steps) throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(obj.toUiSelector());
        if (isVertical) {
            scrollable.setAsVerticalList();
        } else {
            scrollable.setAsHorizontalList();
        }
        return scrollable.scrollToEnd(maxSwipes, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean scrollTo(Selector obj, Selector targetObj, boolean isVertical) throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(obj.toUiSelector());
        if (isVertical) {
            scrollable.setAsVerticalList();
        } else {
            scrollable.setAsHorizontalList();
        }
        return scrollable.scrollIntoView(targetObj.toUiSelector());
    }

    private String addUiObject(UiObject obj) {
        String key = UUID.randomUUID().toString();
        this.uiObjects.put(key, obj);
        Timer clearTimer = new Timer();
        clearTimer.schedule(new ClearUiObjectTimerTask(key), 60000L);
        return key;
    }

    class ClearUiObjectTimerTask extends TimerTask {
        String name;

        public ClearUiObjectTimerTask(String name) {
            this.name = name;
        }

        @Override // java.util.TimerTask, java.lang.Runnable
        public void run() {
            AutomatorServiceImpl.this.uiObjects.remove(this.name);
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String childByText(Selector collection, Selector child, String text) throws UiObjectNotFoundException {
        UiObject obj;
        if (exist(collection) && objInfo(collection).isScrollable()) {
            obj = new UiScrollable(collection.toUiSelector()).getChildByText(child.toUiSelector(), text);
        } else {
            obj = new UiCollection(collection.toUiSelector()).getChildByText(child.toUiSelector(), text);
        }
        return addUiObject(obj);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String childByText(Selector collection, Selector child, String text, boolean allowScrollSearch) throws UiObjectNotFoundException {
        UiObject obj = new UiScrollable(collection.toUiSelector()).getChildByText(child.toUiSelector(), text, allowScrollSearch);
        return addUiObject(obj);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String childByDescription(Selector collection, Selector child, String text) throws UiObjectNotFoundException {
        UiObject obj;
        if (exist(collection) && objInfo(collection).isScrollable()) {
            obj = new UiScrollable(collection.toUiSelector()).getChildByDescription(child.toUiSelector(), text);
        } else {
            obj = new UiCollection(collection.toUiSelector()).getChildByDescription(child.toUiSelector(), text);
        }
        return addUiObject(obj);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String childByDescription(Selector collection, Selector child, String text, boolean allowScrollSearch) throws UiObjectNotFoundException {
        UiObject obj = new UiScrollable(collection.toUiSelector()).getChildByDescription(child.toUiSelector(), text, allowScrollSearch);
        return addUiObject(obj);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String childByInstance(Selector collection, Selector child, int instance) throws UiObjectNotFoundException {
        UiObject obj;
        if (exist(collection) && objInfo(collection).isScrollable()) {
            obj = new UiScrollable(collection.toUiSelector()).getChildByInstance(child.toUiSelector(), instance);
        } else {
            obj = new UiCollection(collection.toUiSelector()).getChildByInstance(child.toUiSelector(), instance);
        }
        return addUiObject(obj);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String getChild(String obj, Selector selector) throws UiObjectNotFoundException {
        UiObject ui = this.uiObjects.get(obj);
        if (ui != null) {
            return addUiObject(ui.getChild(selector.toUiSelector()));
        }
        return null;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String getFromParent(String obj, Selector selector) throws UiObjectNotFoundException {
        UiObject ui = this.uiObjects.get(obj);
        if (ui != null) {
            return addUiObject(ui.getFromParent(selector.toUiSelector()));
        }
        return null;
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String getUiObject(Selector selector) throws UiObjectNotFoundException {
        return addUiObject(this.device.findObject(selector.toUiSelector()));
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void removeUiObject(String obj) {
        this.uiObjects.remove(obj);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String[] getUiObjects() {
        Set<String> strings = this.uiObjects.keySet();
        return (String[]) strings.toArray(new String[strings.size()]);
    }

    private UiObject getUiObject(String name) throws UiObjectNotFoundException {
        if (this.uiObjects.containsKey(name)) {
            return this.uiObjects.get(name);
        }
        throw new UiObjectNotFoundException("UiObject " + name + " not found!");
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void clearTextField(String obj) throws UiObjectNotFoundException {
        getUiObject(obj).clearTextField();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String getText(String obj) throws UiObjectNotFoundException {
        return getUiObject(obj).getText();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean setText(String obj, String text) throws UiObjectNotFoundException {
        return getUiObject(obj).setText(text);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean click(String obj) throws UiObjectNotFoundException {
        return getUiObject(obj).click();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean click(String obj, String corner) throws UiObjectNotFoundException {
        return click(getUiObject(obj), corner);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean clickAndWaitForNewWindow(String obj, long timeout) throws UiObjectNotFoundException {
        return getUiObject(obj).clickAndWaitForNewWindow(timeout);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean longClick(String obj) throws UiObjectNotFoundException {
        return getUiObject(obj).longClick();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean longClick(String obj, String corner) throws UiObjectNotFoundException {
        return longClick(getUiObject(obj), corner);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean dragTo(String obj, Selector destObj, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return dragTo(getUiObject(obj), destObj, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean dragTo(String obj, int destX, int destY, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return dragTo(getUiObject(obj), destX, destY, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean exist(String obj) {
        try {
            return getUiObject(obj).exists();
        } catch (UiObjectNotFoundException e) {
            return false;
        }
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public ObjInfo objInfo(String obj) throws UiObjectNotFoundException {
        return ObjInfo.getObjInfo(getUiObject(obj));
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean gesture(String obj, Point startPoint1, Point startPoint2, Point endPoint1, Point endPoint2, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return gesture(getUiObject(obj), startPoint1, startPoint2, endPoint1, endPoint2, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean pinchIn(String obj, int percent, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return pinchIn(getUiObject(obj), percent, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean pinchOut(String obj, int percent, int steps) throws UiObjectNotFoundException, NotImplementedException {
        return pinchOut(getUiObject(obj), percent, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean swipe(String obj, String dir, int steps) throws UiObjectNotFoundException {
        return swipe(getUiObject(obj), dir, steps);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean waitForExists(String obj, long timeout) throws UiObjectNotFoundException {
        return getUiObject(obj).waitForExists(timeout);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public boolean waitUntilGone(String obj, long timeout) throws UiObjectNotFoundException {
        return getUiObject(obj).waitUntilGone(timeout);
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public ConfiguratorInfo getConfigurator() throws NotImplementedException {
        return new ConfiguratorInfo();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public ConfiguratorInfo setConfigurator(ConfiguratorInfo info) throws NotImplementedException {
        ConfiguratorInfo.setConfigurator(info);
        return new ConfiguratorInfo();
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public void setClipboard(String label, String text) {
        android.content.ClipboardManager cm = (android.content.ClipboardManager) this.mInstrumentation.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText(label, text));
    }

    @Override // com.wetest.uia2.stub.AutomatorService
    public String getClipboard() {
        CharSequence s = this.clipboardManager.getText();
        if (s == null) {
            return null;
        }
        return s.toString();
    }
}